<template>
  <div class="message-manage-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>留言管理</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          @click="handleRefresh"
        >刷新</el-button>
      </div>
      
      <!-- 搜索区域 -->
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="留言内容">
          <el-input v-model="queryParams.content" placeholder="请输入留言内容" clearable></el-input>
        </el-form-item>
        <el-form-item label="回复状态">
          <el-select v-model="queryParams.hasReply" placeholder="请选择回复状态" clearable>
            <el-option label="已回复" :value="true"></el-option>
            <el-option label="未回复" :value="false"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 表格区域 -->
      <el-table
        :data="messageList"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column type="index" width="50" label="#"></el-table-column>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="username" label="用户名" width="120"></el-table-column>
        <el-table-column prop="content" label="留言内容" show-overflow-tooltip></el-table-column>
        <el-table-column prop="messageTime" label="留言时间" width="160" :formatter="formatDate"></el-table-column>
        <el-table-column label="回复状态" width="100">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.reply">已回复</el-tag>
            <el-tag type="danger" v-else>未回复</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleReply(scope.row)"
            >{{ scope.row.reply ? '查看回复' : '回复' }}</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="pagination"
      >
      </el-pagination>
    </el-card>
    
    <!-- 回复对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
      <div class="message-detail">
        <div class="message-info">
          <div class="message-header">
            <div class="user-info">
              <i class="el-icon-user"></i>
              <span class="username">{{ currentMessage.username }}</span>
            </div>
            <span class="message-time">{{ formatDate(null, currentMessage.messageTime) }}</span>
          </div>
          <div class="message-content">{{ currentMessage.content }}</div>
        </div>
        
        <div class="reply-form" v-if="!currentMessage.reply">
          <el-form :model="replyForm" :rules="replyRules" ref="replyFormRef" label-width="0px">
            <el-form-item prop="reply">
              <el-input
                type="textarea"
                :rows="4"
                placeholder="请输入回复内容..."
                v-model="replyForm.reply"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
        
        <div class="reply-info" v-else>
          <div class="reply-header">
            <i class="el-icon-s-custom"></i>
            <span class="admin-name">管理员回复</span>
            <span class="reply-time">{{ formatDate(null, currentMessage.replyTime) }}</span>
          </div>
          <div class="reply-content">{{ currentMessage.reply }}</div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReply" v-if="!currentMessage.reply" :loading="submitLoading">提交回复</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment'

export default {
  name: 'MessageManage',
  data() {
    return {
      // 查询参数
      queryParams: {
        content: '',
        hasReply: null
      },
      // 留言列表
      messageList: [],
      // 加载状态
      loading: false,
      // 分页参数
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 对话框
      dialogVisible: false,
      dialogTitle: '回复留言',
      // 当前选中的留言
      currentMessage: {},
      // 回复表单
      replyForm: {
        reply: ''
      },
      // 回复表单验证规则
      replyRules: {
        reply: [
          { required: true, message: '请输入回复内容', trigger: 'blur' },
          { min: 2, max: 500, message: '长度在 2 到 500 个字符', trigger: 'blur' }
        ]
      },
      // 提交回复加载状态
      submitLoading: false
    }
  },
  created() {
    // 获取留言列表
    this.getMessageList()
  },
  methods: {
    // 获取留言列表
    async getMessageList() {
      this.loading = true
      try {
        const { data: res } = await this.$http.get('/message/list', {
          params: {
            page: this.currentPage,
            size: this.pageSize,
            content: this.queryParams.content || null,
            hasReply: this.queryParams.hasReply
          }
        })
        if (res.code === 200) {
          this.messageList = res.data.records || []
          this.total = res.data.total || 0
        } else {
          this.$message.error(res.message || '获取留言列表失败')
        }
      } catch (error) {
        console.error('获取留言列表失败', error)
        this.$message.error('获取留言列表失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    // 处理查询
    handleQuery() {
      this.currentPage = 1
      this.getMessageList()
    },
    // 重置查询
    resetQuery() {
      this.queryParams = {
        content: '',
        hasReply: null
      }
      this.handleQuery()
    },
    // 刷新
    handleRefresh() {
      this.getMessageList()
    },
    // 处理回复
    handleReply(row) {
      this.currentMessage = { ...row }
      this.dialogTitle = row.reply ? '查看回复' : '回复留言'
      this.dialogVisible = true
      if (!row.reply) {
        this.replyForm.reply = ''
        // 在下一个事件循环中重置表单验证
        this.$nextTick(() => {
          if (this.$refs.replyFormRef) {
            this.$refs.replyFormRef.resetFields()
          }
        })
      }
    },
    // 提交回复
    submitReply() {
      this.$refs.replyFormRef.validate(async valid => {
        if (!valid) return
        this.submitLoading = true
        try {
          // 发送回复请求
          const { data: res } = await this.$http.put(`/message/reply/${this.currentMessage.id}`, {
            reply: this.replyForm.reply
          })
          if (res.code === 200) {
            this.$message.success('回复成功')
            this.dialogVisible = false
            // 刷新留言列表
            this.getMessageList()
          } else {
            this.$message.error(res.message || '回复失败')
          }
        } catch (error) {
          console.error('回复失败', error)
          this.$message.error('回复失败，请稍后重试')
        } finally {
          this.submitLoading = false
        }
      })
    },
    // 处理删除
    handleDelete(row) {
      this.$confirm('确认删除该留言吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const { data: res } = await this.$http.delete(`/message/${row.id}`)
          if (res.code === 200) {
            this.$message.success('删除成功')
            // 刷新留言列表
            this.getMessageList()
          } else {
            this.$message.error(res.message || '删除失败')
          }
        } catch (error) {
          console.error('删除失败', error)
          this.$message.error('删除失败，请稍后重试')
        }
      }).catch(() => {
        // 取消删除
      })
    },
    // 处理页码变化
    handleCurrentChange(newPage) {
      this.currentPage = newPage
      this.getMessageList()
    },
    // 处理每页条数变化
    handleSizeChange(newSize) {
      this.pageSize = newSize
      this.currentPage = 1
      this.getMessageList()
    },
    // 格式化日期
    formatDate(row, dateStr) {
      if (row) {
        return moment(row.messageTime).format('YYYY-MM-DD HH:mm')
      }
      return moment(dateStr).format('YYYY-MM-DD HH:mm')
    }
  }
}
</script>

<style scoped>
.message-manage-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.message-detail {
  margin-bottom: 20px;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.user-info {
  display: flex;
  align-items: center;
}

.username {
  margin-left: 5px;
  font-weight: bold;
  color: #409EFF;
}

.message-time {
  font-size: 12px;
  color: #909399;
}

.message-content {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  line-height: 1.6;
  margin-bottom: 15px;
}

.reply-form {
  margin-top: 20px;
}

.reply-info {
  margin-top: 20px;
}

.reply-header {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.admin-name {
  margin-left: 5px;
  font-weight: bold;
  color: #67c23a;
}

.reply-time {
  font-size: 12px;
  color: #909399;
  margin-left: 10px;
}

.reply-content {
  padding: 10px;
  background-color: #f0f9eb;
  border-radius: 4px;
  line-height: 1.6;
}
</style>